package com.mycalendar;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import constants.Constants;
import utils.DataUtils;
import utils.TimeUtils;
import data.DateInfo;
import adapter.CalendarAdapter;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 主界面
 * */
public class MainActivity extends Activity {

	/**
	 * 和viewpager相关变量
	 * */
	public MyViewPager viewPager = null;
	public MyPagerAdapter pagerAdapter = null;
	private int currPager = 500;

	/**
	 * 和日历gridview相关变量
	 * */
	private GridView gridView = null;
	public CalendarAdapter adapter = null;
	private GridView currentView = null;
	public List<DateInfo> currList = null;
	public List<DateInfo> list = null;
	public int lastSelected = 0;

	// 功能区
	private Button next = null;
	private Button previous = null;
	private Button gotoPage = null;
	private Spinner topLeft = null;
	private Spinner topRight = null;
	private Spinner topCenter = null;
	private Spinner bottomLeft = null;
	private Spinner bottomRight = null;
	private Spinner bottomCenter = null;
	private int selectedYear = -1;
	private int selectedMonth = -1;

	/**
	 * 显示年月
	 * */
	public TextView showYearMonth = null;

	/**
	 * 第一个页面的年月
	 * */
	private int currentYear;
	private int currentMonth;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		long time = System.currentTimeMillis();
		setContentView(R.layout.activity_main);
		initData();
		initView();
		initActionBar();
		initViewPagerOperations();
		initButtonsOperations();
		initSpinnersOperations();
		Log.e("onCreate time:", (System.currentTimeMillis() - time) + "ms");
	}

	private void initActionBar() {
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		setOverflowShowingAlways();
	}

	private void initSpinnersOperations() {
		ArrayAdapter<String> stringAdapter;
		ArrayAdapter<Integer> integerAdapter;

		integerAdapter = new ArrayAdapter<Integer>(this,
				android.R.layout.simple_spinner_item, Constants.years);
		integerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		bottomLeft.setAdapter(integerAdapter);
		bottomLeft.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				selectedYear = Constants.years[arg2];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				selectedYear = -1;
			}
		});

		integerAdapter = new ArrayAdapter<Integer>(this,
				android.R.layout.simple_spinner_item, Constants.months);
		integerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		bottomCenter.setAdapter(integerAdapter);
		bottomCenter.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				selectedMonth = Constants.months[arg2];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				selectedMonth = -1;
			}
		});

		stringAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, Constants.moments);
		stringAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		bottomRight.setAdapter(stringAdapter);

		stringAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, Constants.arr1);
		stringAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		topLeft.setAdapter(stringAdapter);

		stringAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, Constants.arr2);
		stringAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		topRight.setAdapter(stringAdapter);

		stringAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, Constants.arr3);
		stringAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		topCenter.setAdapter(stringAdapter);
	}

	private void initButtonsOperations() {
		previous.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				viewPager.arrowScroll(ViewPager.FOCUS_BACKWARD);
			}
		});
		next.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				viewPager.arrowScroll(ViewPager.FOCUS_FORWARD);
			}
		});
		gotoPage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (selectedYear > 0 && selectedMonth > 0) {
					int position = 500 + (selectedYear - currentYear) * 12
							+ (selectedMonth - currentMonth);
					viewPager.setCurrentItem(position);
				}
			}
		});
	}

	private void initViewPagerOperations() {
		String formatDate = TimeUtils.getFormatDate(currentYear, currentMonth);
		viewPager.setLinesCount(TimeUtils.getLinesCount(formatDate,
				currentMonth));

		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			public void onPageScrollStateChanged(int arg0) {
				switch (arg0) {
				case 0:
					currentView = (GridView) viewPager.findViewById(currPager);
					if (currentView != null) {
						adapter = (CalendarAdapter) currentView.getAdapter();
						currList = adapter.getList();
						int pos = DataUtils.getDayFlag(currList, lastSelected);
						adapter.setSelectedPosition(pos);
						adapter.notifyDataSetInvalidated();
					}
					break;
				default:
					break;
				}
			}

			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			public void onPageSelected(int position) {
				int year = TimeUtils.getTimeByPosition(position, currentYear,
						currentMonth, "year");
				int month = TimeUtils.getTimeByPosition(position, currentYear,
						currentMonth, "month");
				showYearMonth.setText(String.format("%04d年%02d月", year, month));
				currPager = position;
				String formatDate = TimeUtils.getFormatDate(year, month);
				viewPager.setLinesCount(TimeUtils.getLinesCount(formatDate,
						month));
			}
		});
	}

	/**
	 * 初始化view
	 * */
	private void initView() {
		viewPager = (MyViewPager) findViewById(R.id.viewpager);
		pagerAdapter = new MyPagerAdapter();
		viewPager.setAdapter(pagerAdapter);
		viewPager.setCurrentItem(500);
		viewPager.setPageMargin(0);
		showYearMonth = (TextView) findViewById(R.id.main_year_month);
		showYearMonth.setText(String.format("%04d年%02d月", currentYear,
				currentMonth));

		next = (Button) findViewById(R.id.go_next_month);
		previous = (Button) findViewById(R.id.go_previous_month);
		gotoPage = (Button) findViewById(R.id.go_selected_month);
		topLeft = (Spinner) findViewById(R.id.spinner_top_1);
		topRight = (Spinner) findViewById(R.id.spinner_top_2);
		topCenter = (Spinner) findViewById(R.id.spinner_center);
		bottomLeft = (Spinner) findViewById(R.id.spinner_bottom_1);
		bottomRight = (Spinner) findViewById(R.id.spinner_bottom_3);
		bottomCenter = (Spinner) findViewById(R.id.spinner_bottom_2);
	}

	/**
	 * 初始化数据
	 * */
	private void initData() {
		currentYear = TimeUtils.getCurrentYear();
		currentMonth = TimeUtils.getCurrentMonth();
		lastSelected = TimeUtils.getCurrentDay();
		String formatDate = TimeUtils.getFormatDate(currentYear, currentMonth);
		try {
			// list = TimeUtils.initCalendar(formatDate, currentMonth);
			list = TimeUtils.initMyCalendar(formatDate, currentMonth);
		} catch (Exception e) {
			finish();
		}
	}

	/**
	 * 初始化日历的gridview
	 * */
	private GridView initCalendarView(int position) {
		int year = TimeUtils.getTimeByPosition(position, currentYear,
				currentMonth, "year");
		int month = TimeUtils.getTimeByPosition(position, currentYear,
				currentMonth, "month");
		String formatDate = TimeUtils.getFormatDate(year, month);

		try {
			// list = TimeUtils.initCalendar(formatDate, month);
			list = TimeUtils.initMyCalendar(formatDate, month);
		} catch (Exception e) {
			finish();
		}

		gridView = new GridView(this);
		adapter = new CalendarAdapter(this, list);
		if (position == 500) {
			currList = list;
			int pos = DataUtils.getDayFlag(list, lastSelected);
			adapter.setSelectedPosition(pos);
		}
		gridView.setAdapter(adapter);
		gridView.setNumColumns(7);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridView.setGravity(Gravity.CENTER);
		gridView.setOnItemClickListener(new OnItemClickListenerImpl(adapter,
				this));
		gridView.setHorizontalSpacing(1);
		gridView.setVerticalSpacing(1);
		return gridView;
	}

	/**
	 * viewpager的适配器，从第500页开始，最多支持0-1000页
	 * */
	private class MyPagerAdapter extends PagerAdapter {

		@Override
		public void setPrimaryItem(ViewGroup container, int position,
				Object object) {
			currentView = (GridView) object;
			adapter = (CalendarAdapter) currentView.getAdapter();
		}

		@Override
		public int getCount() {
			return 1000;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			GridView gv = initCalendarView(position);
			gv.setId(position);
			container.addView(gv);
			return gv;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * 菜单事件
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_phone_call:
			Toast.makeText(this, "PhoneCalls", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.action_contacts:
			Toast.makeText(this, "Contacts", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.action_settings:
			Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.action_menu_1:
			Toast.makeText(this, "menu1", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.action_menu_2:
			Toast.makeText(this, "menu2", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.action_menu_3:
			Toast.makeText(this, "menu3", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.action_menu_4:
			Toast.makeText(this, "menu4", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.action_menu_5:
			Toast.makeText(this, "menu5", Toast.LENGTH_SHORT).show();
			return true;
		case android.R.id.home:
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * 设置菜单总是同时显示图标和文字
	 */
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod(
							"setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
				}
			}
		}
		return super.onMenuOpened(featureId, menu);
	}

	/**
	 * 设置菜单总是从上面出来
	 */
	private void setOverflowShowingAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKeyField.setAccessible(true);
			menuKeyField.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
